package com.hnichr.ump.talent.library.provider.impl;

import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.hnichr.ump.common.talent.library.entity.LanguageLevel;
import com.hnichr.ump.common.talent.library.service.LanguageLevelService;
import com.hnichr.ump.talent.library.provider.SyncPolicyProvider;
import org.apache.commons.collections4.CollectionUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.transaction.annotation.Transactional;

import java.util.Date;

@Component
public class LanguageLevelSyncPolicyProvider implements SyncPolicyProvider {
    private static final String KEY = "languageLevelList";

    @Autowired
    private LanguageLevelService languageLevelService;

    @Override
    public boolean support(JSONObject jsonObject) {
        return jsonObject.containsKey(KEY);
    }

    @Override
    @Transactional
    public void sync(String syncDate, JSONObject jsonObject) {
        JSONArray languageList = jsonObject.getJSONArray(KEY);
        if(CollectionUtils.isEmpty(languageList)){
            return;
        }
        for(Object languageObject:languageList){
            if(languageObject instanceof JSONObject){
                JSONObject language = (JSONObject) languageObject;
                LanguageLevel languageLevel = new LanguageLevel();
                languageLevel.setId(language.getString("id"));
                languageLevel.setDelFlag(language.getBoolean("delFlag"));
                languageLevel.setUserId(language.getString("userId"));
                if(language.containsKey("createTime")){
                    languageLevel.setOrginalCreateTime(new Date(language.getLong("createTime")));
                }
                if(language.containsKey("updateTime")){
                    languageLevel.setOrginalUpdateTime(new Date(language.getLong("updateTime")));
                }

                languageLevel.setType(language.getString("type"));
                languageLevel.setOralLanguageLevel(language.getString("oralLanguageLevel"));
                languageLevel.setReadingLevel(language.getString("readingLevel"));
                languageLevel.setResumeId(language.getString("resumeId"));
                languageLevel.setSyncDate(syncDate);
                languageLevelService.merge(languageLevel);
            }
        }
    }
}
